package nxu.it.movieapi.service.pg;

import nxu.it.api.common.result.Pageable;
import nxu.it.api.model.*;
import nxu.it.api.service.MovieCastService;
import nxu.it.api.service.StaffService;
import nxu.it.api.service.param.StaffPageQueryParam;
import nxu.it.movieapi.service.pg.dao.StaffPgDao;
import org.jdbi.v3.core.Jdbi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
public class StaffServicePgImpl implements StaffService {
    private final Jdbi jdbi;
    private final MovieCastService movieCastService;

    @Autowired
    public StaffServicePgImpl(@Qualifier("createSecondJdbi") Jdbi jdbi, MovieCastService movieCastService) {
        this.jdbi = jdbi;
        this.movieCastService = movieCastService;
    }

    @Override
    public Optional<Staff> findById(Integer staffId) {
        StaffPgDao dao = jdbi.onDemand(StaffPgDao.class);
        Optional<Staff> staffOpt = dao.findById(staffId);

        if (staffOpt.isPresent()) {
            Staff staff = staffOpt.get();
            List<Filmography> actedMovies = movieCastService.findMoviesByStaffIdAndRole(staffId, CastRole.ACTOR);
            List<Filmography> directedMovies = movieCastService.findMoviesByStaffIdAndRole(staffId, CastRole.DIRECTOR);

            staff.setActed(actedMovies);
            staff.setDirected(directedMovies);

            return Optional.of(staff);
        }

        return Optional.empty();
    }

    @Override
    public Pageable<SimpleStaff> page(StaffPageQueryParam pageQueryParam) {
        String whereClause = buildWhereClause(pageQueryParam);
        String orderByClause = "id ASC"; // 或者根据实际需求调整排序字段
        int size = pageQueryParam.getPageSize();
        int page = pageQueryParam.getPageNumber();
        int offset = (page - 1) * size;

        List<SimpleStaff> simpleStaffList = jdbi.withExtension(StaffPgDao.class, dao -> dao.complexPage(whereClause, orderByClause, pageQueryParam.getEnglishName(), pageQueryParam.getChineseName(), pageQueryParam.getRegion(), pageQueryParam.getGender(), size, offset));
        int totalRows = jdbi.withExtension(StaffPgDao.class, dao -> dao.complexCount(whereClause));
        int totalPages = (int) Math.ceil((double) totalRows / size);

        return new Pageable<SimpleStaff>() {
            @Override
            public int getTotalRow() {
                return totalRows;
            }

            @Override
            public int getTotalPage() {
                return totalPages;
            }

            @Override
            public int getPageSize() {
                return size;
            }

            @Override
            public int getPageNumber() {
                return page;
            }

            @Override
            public List<SimpleStaff> getList() {
                return simpleStaffList;
            }
        };
    }
    private String buildWhereClause(StaffPageQueryParam pageQueryParam) {
        StringBuilder whereClause = new StringBuilder("WHERE 1=1");

        if (pageQueryParam.getEnglishName() != null) {
            whereClause.append(" AND english_name LIKE '%").append(pageQueryParam.getEnglishName()).append("%'");
        }
        if (pageQueryParam.getChineseName() != null) {
            whereClause.append(" AND chinese_name LIKE '%").append(pageQueryParam.getChineseName()).append("%'");
        }
        if (pageQueryParam.getRegion() != null) {
            whereClause.append(" AND region = '").append(pageQueryParam.getRegion()).append("'");
        }
        if (pageQueryParam.getGender() != null) {
            whereClause.append(" AND gender = '").append(pageQueryParam.getGender()).append("'");
        }

        return whereClause.toString();
    }
}